package com.yichuang.security.jwt.main.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.MacSigner;
import org.springframework.security.jwt.crypto.sign.Signer;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.common.util.JsonParser;
import org.springframework.security.oauth2.common.util.JsonParserFactory;

import java.util.Map;

/**
 * <p> spring security oauth2 内部的token编码/解码工具类，参考JwtAccessTokenConverter </p>
 *
 * @author tuonioooo
 * @site https://miliqkdoc.motopa.cn/
 * @date 2020/6/29 21:07
 */
@Slf4j
public class JwtAccessTokenConverterUtils {

    final static String EXP = "exp";

    /**
     * token 编码
     *
     * @param content     内容
     * @param verifierKey 签名的密钥
     * @return
     */
    public static String encode(String content, String verifierKey) {
        Signer signer = new MacSigner(verifierKey);
        String token = JwtHelper.encode(content, signer).getEncoded();
        System.out.println("token = " + token);
        log.info("JwtAccessTokenConverterUtils——>token={}", token);
        return token;
    }

    /**
     * token 解码
     *
     * @param token token
     */
    public static Map<String, Object> decode(String token) {
        try {
            JsonParser objectMapper = JsonParserFactory.create();
            //JwtHelper.decodeAndVerify(token, verifierKey);
            Jwt jwt = JwtHelper.decode(token);
            String claimsStr = jwt.getClaims();
            Map<String, Object> claims = objectMapper.parseMap(claimsStr);
            if (claims.containsKey(EXP) && claims.get(EXP) instanceof Integer) {
                Integer intValue = (Integer) claims.get(EXP);
                claims.put(EXP, new Long(intValue));
            }
            log.info("JwtAccessTokenConverterUtils——>claims={}", claims);
            return claims;
        } catch (Exception e) {
            throw new InvalidTokenException("Cannot convert access token to JSON", e);
        }
    }
}
